# -*- coding: utf-8 -*-
#author by makunkun tel:17756566660
from HuobiDMService import HuobiDM
import time

class arbitrage():
    
    def __init__(self,ACCESS_KEY,SECRET_KEY):
        # URL = 'https://api.hbdm.com'
        URL = 'https://api.btcgateway.pro'
        # self.URL = 'api.btcgateway.pro'
        # self.ACCESS_KEY = ACCESS_KEY
        # self.SECRET_KEY = SECRET_KEY
        self.dm = HuobiDM(URL, ACCESS_KEY, SECRET_KEY)

    def datas(self,pp1,pp2):
        while True:
            try:
                a = self.dm.get_contract_depth(pp1, 'step6')
                b = self.dm.get_contract_depth(pp2, 'step6')
                a1 = b.get('tick').get('asks')[0][0]
                a2 = a.get('tick').get('bids')[0][0]
                a3 = b.get('tick').get('bids')[0][0]
                a4 = a.get('tick').get('asks')[0][0]
                dif1 = (a3-a4)/a4
                dif2 = (a1-a2)/a2
                return dif1,dif2
                break
            except:
                time.sleep(2)
                continue
    def openn(self,p1,p2,diff,amount,rate,add,amount_p1,amount_p2,direction):
        print('开仓 ',p1,' && ', p2)
        print(str(diff),str(amount),str(add),str(amount_p2),str(amount_p1))
        # p1='BTC_NW'
        # p2='ETH_CQ'
        symbol = p1[:3]
        dit ={'CW':['this_week',1],'NW':['next_week',2],'CQ':['quarter',3],'NQ':['next_quarter',4]}
        if dit.get(p1[-2:])[1] < dit.get(p2[-2:])[1] :
            number = 0
            n = int(amount/min(amount_p1,amount_p2)) 
            while True:
                cc=list(self.datas(p1,p2))
                if cc[0]>diff and number<n :
                    orders_data = {'orders_data': [
                       {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                        'volume':amount_p2, 'direction':'sell', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'},
                       {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                        'volume':amount_p1, 'direction':'buy', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
#                    print(str(orders_data))
                    open_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        open_order.get('data').get('success')[0].get('order_id_str')
                        number += 1
                        print(str(diff)+'--'+str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(open_order.get('data').get('errors')[0].get('err_code')))
                        print(str(open_order.get('data').get('errors')[0].get('err_msg')))
                        break
                if not add and number == n:
                    print('建仓结束')
                    break
                if add and number == n and direction==1:
                    self.dm.send_contract_order(symbol=symbol, contract_type=dit.get(p2[-2:])[0], contract_code='',client_order_id='',price='',
                                                  volume=add, direction='sell',offset='open', lever_rate=rate, order_price_type='optimal_10')
                    print('已经加仓'+str(add)+'张--空单')
                    break
                if add and number == n and direction==2:
                    self.dm.send_contract_order(symbol=symbol, contract_type=dit.get(p2[-2:])[0], contract_code='',client_order_id='',price='',
                                                  volume=add, direction='buy',offset='close', lever_rate=rate, order_price_type='optimal_10')
                    print('已经平仓'+str(add)+'张--空单')
                    break
                time.sleep(1)
        if dit.get(p1[-2:])[1] > dit.get(p2[-2:])[1] :
            number = 0
            n = int(amount/min(amount_p1,amount_p2)) 
            while True:
                cc=list(self.datas(p2,p1))
                if cc[1] <diff and number<n :
                    orders_data = {'orders_data': [
                       {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                        'volume':amount_p2, 'direction':'sell', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'},
                       {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                        'volume':amount_p1, 'direction':'buy', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    open_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        open_order.get('data').get('success')[0].get('order_id_str')
                        number += 1
                        print(str(diff)+'--'+str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(open_order.get('data').get('errors')[0].get('err_code')))
                        print(str(open_order.get('data').get('errors')[0].get('err_msg')))
                        break
                if not add and number == n:
                    print('建仓结束')
                    break
                if number == n and direction==1:
                    self.dm.send_contract_order(symbol=symbol, contract_type=dit.get(p1[-2:])[0], contract_code='',client_order_id='',price='',
                                                  volume=add, direction='buy',offset='open', lever_rate=rate, order_price_type='optimal_10')
                    print('已经加仓'+str(add)+'张--多单')
                    break
                if number == n and direction==2:
                    self.dm.send_contract_order(symbol=symbol, contract_type=dit.get(p1[-2:])[0], contract_code='',client_order_id='',price='',
                                                  volume=add, direction='sell',offset='close', lever_rate=rate, order_price_type='optimal_10')
                    print('已经平仓'+str(add)+'张--多单')
                    break
                time.sleep(1)
                
    def close(self,p1,p2,diff,amount,rate,amount_p1,amount_p2):
        print('平仓 ',p1,' && ', p2)
        print(str(diff),str(amount))
        symbol = p1[:3]
        dit ={'CW':['this_week',1],'NW':['next_week',2],'CQ':['quarter',3],'NQ':['next_quarter',4]}
        if dit.get(p1[-2:])[1] < dit.get(p2[-2:])[1] :
            number = 0
            n = int(amount/min(amount_p1,amount_p2)) 
            while True:
                cc=list(self.datas(p1,p2))
                if cc[1]<diff and number<n :
                    orders_data = {'orders_data': [
                       {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                        'volume':amount_p2, 'direction':'buy', 'offset':'close', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'},
                       {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                        'volume':amount_p1, 'direction':'sell', 'offset':'close', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    close_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        close_order.get('data').get('success')[0].get('order_id_str')
                        number += 1
                        print(str(diff)+'--'+str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(close_order.get('data').get('errors')[0].get('err_code')))
                        print(str(close_order.get('data').get('errors')[0].get('err_msg')))
                        break
                if number == n :
                    print('平仓完成')
                    break
                time.sleep(1)
        if dit.get(p1[-2:])[1] > dit.get(p2[-2:])[1] :
            number = 0
            n = int(amount/min(amount_p1,amount_p2)) 
            while True:
                cc=list(self.datas(p2,p1))
                if cc[0] > diff and number<n :
                    orders_data = {'orders_data': [
                       {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                        'volume':amount_p2, 'direction':'buy', 'offset':'close', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'},
                       {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                        'volume':amount_p1, 'direction':'sell', 'offset':'close', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    close_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        close_order.get('data').get('success')[0].get('order_id_str')
                        number += 1
                        print(str(diff)+'--'+str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(close_order.get('data').get('errors')[0].get('err_code')))
                        print(str(close_order.get('data').get('errors')[0].get('err_msg')))
                        break
                if number == n :
                    print('平仓完成')
                    break
                time.sleep(1)
                
    def circle(self,p1,p2,open_dif,close_dif,amount,rate,amount_p1,amount_p2):
        print('单向套利 ',p1,' && ', p2)
        print(str(open_dif),str(close_dif),str(amount))
        symbol = p1[:3]
        dit ={'CW':['this_week',1],'NW':['next_week',2],'CQ':['quarter',3],'NQ':['next_quarter',4]}
        if dit.get(p1[-2:])[1] < dit.get(p2[-2:])[1] :
            number = 0
            n = int(amount/min(amount_p1,amount_p2)) 
            while True:
                cc=list(self.datas(p1,p2))
                if cc[0]>open_dif and number<n :
                    orders_data = {'orders_data': [
                       {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                        'volume':amount_p2, 'direction':'sell', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'},
                       {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                        'volume':amount_p1, 'direction':'buy', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    open_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        open_order.get('data').get('success')[0].get('order_id_str')
                        number += 1
                        print(str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(open_order.get('data').get('errors')[0].get('err_code')))
                        print(str(open_order.get('data').get('errors')[0].get('err_msg')))
                        break
                if cc[1]<close_dif and number>0:
                    orders_data = {'orders_data': [
                               {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                                'volume':amount_p2, 'direction':'buy', 'offset':'close', 
                                'leverRate':rate, 'orderPriceType':'optimal_10'},
                               {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                                'volume':amount_p1, 'direction':'sell', 'offset':'close', 
                                'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    close_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        close_order.get('data').get('success')[0].get('order_id_str')
                        number -= 1
                        print(str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(close_order.get('data').get('errors')[0].get('err_code')))
                        print(str(close_order.get('data').get('errors')[0].get('err_msg')))
                        break
                time.sleep(1)
        if dit.get(p1[-2:])[1] > dit.get(p2[-2:])[1] :
            number = 0
            n = int(amount/min(amount_p1,amount_p2)) 
            while True:
                cc=list(self.datas(p2,p1))
                if cc[1]<open_dif and number<n :
                    orders_data = {'orders_data': [
                       {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                        'volume':amount_p2, 'direction':'sell', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'},
                       {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                        'volume':amount_p1, 'direction':'buy', 'offset':'open', 
                        'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    open_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        open_order.get('data').get('success')[0].get('order_id_str')
                        number += 1
                        print(str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(open_order.get('data').get('errors')[0].get('err_code')))
                        print(str(open_order.get('data').get('errors')[0].get('err_msg')))
                        break
                if cc[0]>close_dif and number>0:
                    orders_data = {'orders_data': [
                               {'symbol': symbol, 'contract_type': dit.get(p2[-2:])[0],  
                                'volume':amount_p2, 'direction':'buy', 'offset':'close', 
                                'leverRate':rate, 'orderPriceType':'optimal_10'},
                               {'symbol': symbol,'contract_type': dit.get(p1[-2:])[0], 
                                'volume':amount_p1, 'direction':'sell', 'offset':'close', 
                                'leverRate':rate, 'orderPriceType':'optimal_10'}]} 
                    close_order = self.dm.send_contract_batchorder(orders_data)
                    try:
                        close_order.get('data').get('success')[0].get('order_id_str')
                        number -= 1
                        print(str(number))
                    except Exception as e:
                        print('注意：下单失败')
                        print(f'error is {e}')
                        print(str(close_order.get('data').get('errors')[0].get('err_code')))
                        print(str(close_order.get('data').get('errors')[0].get('err_msg')))
                        break
                time.sleep(1)
                    


